package com.fx.common.intercept;

import com.fx.common.session.ExceptionHandler;
import com.fx.common.session.ResponseExceptionHandler;
import com.fx.common.session.SessionManage;
import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class AuthBearerIntercept extends BasePathMatchInterceptor {

    private SessionManage sessionManage;

    private ExceptionHandler exceptionHandler;

    private ResponseExceptionHandler responseExceptionHandler;


    public AuthBearerIntercept(SessionManage sessionManage,ExceptionHandler exceptionHandler
            ,ResponseExceptionHandler responseExceptionHandler){
        this.sessionManage = sessionManage;
        this.exceptionHandler = exceptionHandler;
        this.responseExceptionHandler = responseExceptionHandler;
    }

    @Override
    protected Response doIntercept(Chain chain) throws IOException {
        try{
            Response response = null;
            Request request = chain.request();
            String token = sessionManage.getCurrentClientToken();
            if (StringUtils.isBlank(token)){
                response = chain.proceed(request);
            }else{
                Request newReq = request.newBuilder()
                        .addHeader("Authorization", "Bearer "+token)
                        .build();
                response = chain.proceed(newReq);
            }
            if(!response.isSuccessful()) {
                responseExceptionHandler.handler(response.code(),response.body());
            }
            return response;
        }catch (Exception e){
            exceptionHandler.showException(e);
            throw new IOException(e);
        }
    }
}
